//db.js
// YQL
var q1 = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Febox.mcs.csueastbay.edu%3A8080%2Fcs12618%2Fproj1%2Ftwiface%3Fid%3D";
var q2 = "%26getscrname%3Dgetscrname%22%20&format=json&diagnostics=true&callback=";

// insertion query
var qIns1 = "http://query.yahooapis.com/v1/public/yql?q=%20SELECT%20*%20FROM%20json%20WHERE%20url%3D%22http%3A%2F%2Febox.mcs.csueastbay.edu%3A8080%2Fcs12618%2Fproj1%2Ftwiface%3Finsert%3Dinsert%26id%3D";
var qIns2 = "%26scrname%3D";
var qIns3 = "%22%20%20&format=json&diagnostics=true&callback=";

// Query: Fetch Twitter Screen ID
var szQueryScrName = "http://ebox.mcs.csueastbay.edu:8080/cs12618/proj1/twiface?getscrname=&id=";

// Query: Insert Twitter Screen ID
var szQueryInsertData1 = "http://ebox.mcs.csueastbay.edu:8080/cs12618/proj1/twiface?insert=insert&id=";
var szQueryInsertData2 = "&scrname=";

// Query: Update Twitter Screen ID
var szQueryUpdateData1 = "http://ebox.mcs.csueastbay.edu:8080/cs12618/proj1/twiface?update=update&id=";
var szQueryUpdateData2 = "&scrname=";


// function: insert
// we are not worried much about return and call function here
// instead we will check it by exists
function insertOsid(osid, scrname){
	try {
		var URL = qIns1 + osid + qIns2 + scrname + qIns3;
		//alert(URL);
		readURL_db(URL, null, "");
	}catch (ex) {
		showMessage("insertOsid (" + osid +","+scrname+") : " + ex.Message);
	}
}

// function: update
// we are not worried about return and callbacks here
// instead we will use exists()
function updateOsid(osid, scrname){
	try {
		var URL = szQueryUpdateData1 + osid + szQueryUpdateData2 + scrname;
		readURL_db(URL, null, "");
	}catch (ex) {
		showMessage("insertOsid (" + osid +","+scrname+") : " + ex.Message);
	}
}

// function: query
function queryScrName(osid, divid){
	try {
		// reset the text
		document.getElementById(divid).innerHTML = "Twitter ID : ";
		var URL = q1 + osid + q2;
		readURL_db(URL, queryScrNameCallBack, divid, osid);
	} catch (ex) {
		//TODO: handle exceptino
		handleException("queryScrName()" + ex.description);
	}
}

function insertRow(divid){
	// get parameter values 
	var name = document.formAdd.scrname.value;
	// document.formAdd.scrname.value 
	//alert(name);
	// document.formAdd.id.value
	//alert(document.formAdd.id.value);
	// divid;
	//alert(divid.id);
	//call the query
	insertOsid(document.formAdd.id.value, name);
	
	// set the text
	var text = "Twitter ID : ";
	text += "<a href=\"javascript:void()\" onclick=\"javascript:navigateTab(1);getTwitStream('"+name+"', 'twitter');\">"+name+"</a>";
	//alert("PROPOSED\n" + text);
	document.getElementById(divid.id).innerHTML = text;
	//alert("actual \n" + document.getElementById(divid.id).innerHTML);
}

function queryScrNameCallBack(oJSON, divid, osid) {
	if (oJSON != null){
		try{
			var text = "";
			//alert(oJSON.query.results.SCREEN_NAME);
			// case 1: screen name exists, simply use that name 
			showMessage(oJSON.query.count);
			if (oJSON.query.count > 0) {
				var name = oJSON.query.results.SCREEN_NAME;
				text = "Twitter ID : ";
				text += "<a href=\"javascript:void()\" onclick=\"javascript:navigateTab(1);getTwitStream('"+name+"', 'twitter');\">"+name+"</a>";
			} else { // otherwise create a form to add
				/*text = '<form method="GET" onsubmit="javascript:alert(100);" action="javascript:alert(100);">';
				text += 'Twitter ID : <input type="text" name="scrname"/> ';
				text += '<input type="hidden" name="id" value="'+osid+'"/>';
				text += '<input type="submit" name="insert" value="insert"/> </form>';*/
				text = '<form name="formAdd">';
				text += 'Twitter ID : <input type="text" name="scrname"/> ';
				text += '<input type="hidden" name="id" value="'+osid+'"/>';
				text += '<input type="button" name="insert" value="insert" onclick="insertRow('+divid+');"/> </form>';
				
			}
			document.getElementById(divid).innerHTML = text;
		} catch(ex){
			//TODO: handle exceptino
			handleException("queryScrNameCallBack()" + ex.description);
		}
	}
}

/**************************************************************/
// function to fetch URL DATA
// input: URL = to fetch data from
// input: callback = function that handles data
// input: div id to put data
function readURL_db(szURL, callBack, divid, osid) {
	try {
		// create an AJAX request
		var ajaxReq = new XMLHttpRequest();
		// setup a status change
		ajaxReq.onreadystatechange = function() {
			if (ajaxReq.readyState == 4) { // 4 == complete
				// 200 == status OK
				if (ajaxReq.status == 200
						|| window.location.href.indexOf("http") == -1) {
					// if call back function is defined, call it
					if (callBack != null) {
						// convert it to JSON
						var oJSON = gadgets.json.parse(ajaxReq.responseText);
						// give a callback with JSON
						callBack(oJSON, divid, osid);
					}
					// else dont know what to do.
				} else {
					errors += "AJAX: URL : " + szURL + "Status: "
							+ ajaxReq.status + "<br/>";
				}
			}
		};
		
		ajaxReq.open("GET", szURL, true);
		ajaxReq.send(null);
	} catch (ex) {
		handleException("readURL_db()" + ex.description);
	}
}